//
//    rsqd - RsQueue daemon responsible for queue.
//    Copyright (C) 2022  Marcus Pedersén marcus@marcux.org
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

use actix_web::{error, web, Error};
use rusqlite::{Statement, params};

pub type Pool = r2d2::Pool<r2d2_sqlite::SqliteConnectionManager>;
pub type Connection = r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>;

/// Initializes database
/// and creates tables
/// if they do not exist.
/// Returns a pool to be used
/// for queries.
pub fn init_db(db_path: String) -> Result<Pool, String> {
    let manager = r2d2_sqlite::SqliteConnectionManager::file(db_path);
    let pool;
    match Pool::new(manager) {
	Ok(p) => pool = p,
	Err(e) => {
	    return Err(
		format!("Failed to create database connection pool: {e}")
	    );
	}
    }

    let conn;
    match pool.get() {
	Ok(c) => conn = c,
	Err(e) => {
	    return Err(
		format!("Failed to get connection to database: {e}")
	    );
	}
    }

    match conn.execute(
	"CREATE TABLE IF NOT EXISTS validate_host
         (
             id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
             ip TEXT NOT NULL,
             name TEXT NOT NULL,
             key TEXT NOT NULL
         );", params![]) {
        Ok(_) => (),
        Err(e) => {
	    return Err(
		format!("Failed to create table validate_host: {e}")
	    );
	}
    }

    match conn.execute(
	"CREATE TABLE IF NOT EXISTS node
         (
             id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
             name TEXT NOT NULL,
             ip TEXT,
             key TEXT,
             cores INT,
             cores_alloc INT,
             cores_in_use INT,
             ram TEXT,
             ram_free TEXT,
             state TEXT
         );", params![]) {
        Ok(_) => (),
        Err(e) => {
	    return Err(
		format!("Failed to create table node: {e}")
	    );
	}
    }
    
    Ok(pool)
}
